package route

import (
	"gitee.com/linxing_3/sr-core/server/net/http"
	"gitee.com/linxing_3/sr-core/server/net/http/session"
	"gitee.com/mkwchecking/sr-admin/pkg/http/middleware"
	"github.com/gin-gonic/gin"
)

type (
	HttpAuthHandler[A any] func(router *gin.RouterGroup, session *session.SessionManager, api A)
	HttpHandler[A any]     func(router *gin.RouterGroup, api A)
)

type RouterHandler[A any] struct {
	description  string // 描述
	rootPath     string // 根路径
	sessionMgr   *session.SessionManager
	httpEngine   http.IHttpServer
	api          A
	authHandlers []HttpAuthHandler[A]
	handlers     []HttpHandler[A]
}

func NewRouterHandler[A any](api A) *RouterHandler[A] {
	return &RouterHandler[A]{
		api:          api,
		authHandlers: make([]HttpAuthHandler[A], 0),
		handlers:     make([]HttpHandler[A], 0),
	}
}

func (h *RouterHandler[A]) WithDesc(desc string) *RouterHandler[A] {
	h.description = desc
	return h
}

func (h *RouterHandler[A]) WithRootPath(rootPath string) *RouterHandler[A] {
	h.rootPath = rootPath
	return h
}

func (h *RouterHandler[A]) WithHttpEngine(httpEngine http.IHttpServer) *RouterHandler[A] {
	h.httpEngine = httpEngine
	return h
}

func (h *RouterHandler[A]) WithSessionMgr(sessionMgr *session.SessionManager) *RouterHandler[A] {
	h.sessionMgr = sessionMgr
	return h
}

func (h *RouterHandler[A]) WithAuthHandler(authHandlers ...HttpAuthHandler[A]) *RouterHandler[A] {
	h.authHandlers = append(h.authHandlers, authHandlers...)
	return h
}

func (h *RouterHandler[A]) WithHandler(handlers ...HttpHandler[A]) *RouterHandler[A] {
	h.handlers = append(h.handlers, handlers...)
	return h
}

func (h *RouterHandler[A]) Execute() error {
	group := h.httpEngine.Router(h.rootPath, middleware.Cors)
	for _, handler := range h.authHandlers {
		handler(group, h.sessionMgr, h.api)
	}

	for _, handler := range h.handlers {
		handler(group, h.api)
	}

	return nil
}
